package com.zhouyu.service;

import com.zhouyu.mini.spring.BeanPostProcessor;
import com.zhouyu.mini.spring.Component;
import com.zhouyu.mini.spring.PostConstruct;
import com.zhouyu.mini.spring.ZhouyuValue;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @author 周瑜
 */
//@Component
public class ZhouyuValueBeanPostProcessor implements BeanPostProcessor {

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) {

        for (Field field : bean.getClass().getDeclaredFields()) {
            if (field.isAnnotationPresent(ZhouyuValue.class)) {
                field.setAccessible(true);
                try {
                    field.set(bean, field.getAnnotation(ZhouyuValue.class).value());
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        }

        // 初始化前
        for (Method method : bean.getClass().getDeclaredMethods()) {
            if (method.isAnnotationPresent(PostConstruct.class)) {
                method.setAccessible(true);
                try {
                    method.invoke(bean);
                } catch (IllegalAccessException e) {
                    throw new RuntimeException(e);
                } catch (InvocationTargetException e) {
                    throw new RuntimeException(e);
                }
            }
        }

        // bean
        return bean;
    }
}
